import {TYPE, TYPE_CUSTOM} from "@/constant/index.js";
import reportApi from '@/api/modules/report'



/**
 * 判断是否为空
 */
export function isEmpty(str) {
  if (typeof str === 'undefined') return true
  if (str == false) return true
  if (str == 'false') return true
  if (str == null) return true
  if (str === 'null') return true
  if (str === '') return true
  if (JSON.stringify(str) === '[]') return true
  if (JSON.stringify(str) === '{}') return true
  return false
}


/** 获取url中的指定参数值 */
export function getQueryString(name) {
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    let r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    }
    return null;
}

/**
 * 根据身份证获取出生日期（yyyy-MM-dd）
 * @param psidno
 * @returns {birthday:yyyy-MM-dd}
 * @constructor
 */
export function GetBirthday(psidno) {
    var birthdayno, birthdaytemp;
    if (psidno.length == 18) {
        birthdayno = psidno.substring(6, 14);
    } else if (psidno.length == 15) {
        birthdaytemp = psidno.substring(6, 12);
        birthdayno = "19" + birthdaytemp;
    } else {
        return "";
    }
    var birthday = birthdayno.substring(0, 4) + "-" + birthdayno.substring(4, 6) + "-" + birthdayno.substring(6, 8);
    return birthday;
}

/**
 *根据输入的身份证获取性别代码
 * @param psidno
 * @returns {sex}
 * @constructor
 */
export function Getsex(psidno) {
    var sexno, sex;
    if (psidno.length == 18) {
        sexno = psidno.substring(16, 17);
    } else if (psidno.length == 15) {
        sexno = psidno.substring(14, 15);
    } else {
        return "";
    }
    var tempid = sexno % 2;
    if (tempid == 0) {
        sex = "女";
    } else {
        sex = "男";
    }
    return sex;
}

export function isIOS() {
    let u = navigator.userAgent;
    let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    return isiOS;
}

// 格式化时间为年月日
export function formatYmd(value, separ = '-') {
    if (value instanceof Date) {
        let month = (value.getMonth() + 1).toString()
        month = month.padStart(2, '0')
        return (
            value.getFullYear() +
            separ +
            month +
            separ +
            value
                .getDate()
                .toString()
                .padStart(2, '0')
        )
    }
    return ''
}

// 时间 增加年
export function addYear(date, year) {
    if (date instanceof Date) {
        date.setFullYear(date.getFullYear() + year)
    }
    return date
}

// 时间 增加天
export function addDay(date, day) {
    if (date instanceof Date) {
        date.setDate(date.getDate() + day)
    }
    return date
}

// 计算两个日期相差天数
export function getDiffDays(start, end) {
    const diffTime = end.getTime() - start.getTime()
    return diffTime / (1000 * 3600 * 24)
}

// 获取URL中的二维码ID
export function getQrCodeId() {
  const type = getQueryString(TYPE)
  if (!type){
    return null
  }
  if (type.indexOf(TYPE_CUSTOM) === -1) {
    return null
  }
  return type.split(TYPE_CUSTOM)[1]
}

// 获取URL中的二维码类型
export function getQrType() {
  const type = getQueryString(TYPE)
  if (!type) {
    return null
  }
  if (type.indexOf(TYPE_CUSTOM) === -1) {
    return type
  }
  return TYPE_CUSTOM
}

//获取url中的指定参数
export function getUrlParam(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
  var r = window.location.search.substr(1).match(reg);  //匹配目标参数
  if (r != null) return unescape(r[2]); return null; //返回参数值
}

export function getRequest (key) {
  // 获取参数
  var url = window.location.search
  // 正则筛选地址栏
  var reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)')
  // 匹配目标参数
  var result = url.substr(1).match(reg)
  // 返回参数值
  return result ? decodeURIComponent(result[2]) : null
}

// 获取URL Query参数
export function getRequestParam() {
  const urlParams = {}
  const url = window.location.href
  const afterUrl = url.split('#')[0]
  const getParamUrl = afterUrl || url
  const queryParamsStr = getParamUrl.split('?')[1]
  if (queryParamsStr) {
    const queryParams = queryParamsStr.split('&')
    for (let i = 0; i < queryParams.length; i++) {
      const splitItem = queryParams[i].split('=')
      urlParams[splitItem[0]] = splitItem[1]
    }
  }
  return urlParams
}

// 重新微信授权
export async function reauthorize(delParams = ['state', 'deptId', 'code']) {
  let deptId
  let newHref
  try {
    deptId = getQueryString("deptId");
    console.log(deptId)
    newHref = window.location.origin + window.location.pathname + '?deptId='+ deptId
    const reqParam = getRequestParam()
    if (reqParam) {
      delParams.forEach(item => Reflect.deleteProperty(reqParam, item))
      const paramKeys = Object.keys(reqParam);
      if (paramKeys && paramKeys.length > 0) {
        for (let i = 0; i < paramKeys.length; i++) {
          newHref+=`&${paramKeys[i]}=${reqParam[paramKeys[i]]}`
        }
      }
    }
    uni.setStorageSync("ressssssss2", 'reauthorize');
    window.location.href = newHref
  } catch (e) {
    try {
      console.log('重新授权处理错误', e)
      let text = '重新授权处理错误错误 ' + ' \n '
      text += `deptId: ${deptId} \n`
      text += ` href: ${newHref} \n`
      text += ` ex: ${e}  \n `
      text += ` stack: ${e.stack} \n`
      await reportApi.errorReport({error: text, appId: '', openId: '',})
    } catch (ex) {
    }
    uni.setStorageSync("ressssssss2", 'reauthorize2');

    window.location.href = window.location.origin + window.location.pathname + '?deptId='+ deptId
  }
}
